﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace FrameworkSpTest
{
    internal class Program
    {

        //修改串口名称和波特率
        static SerialPort sp = new SerialPort("COM1", 9600);

        static string ReadByBytes()
        {
            int bytes = sp.BytesToRead;
            byte[] buffer = new byte[bytes];
            sp.Read(buffer, 0, bytes);
            return Encoding.Default.GetString(buffer);
        }

        static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //注释下面方法的任意一个，扫码测试，看有没有区别
            string barcode = sp.ReadExisting();
            //string barcode = ReadByBytes();

            Console.WriteLine($"收到串口数据[{barcode}]");


        }
        static void Main(string[] args)
        {
            Console.WriteLine(sp.ToString());
            sp.DataReceived += SerialPort_DataReceived;

            try
            {
                sp.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("现在请测试扫码，并检查数据是否正确，按任意键结束程序。。。");
            Console.ReadKey();
            try
            {
                sp.Close();
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
            }
            Console.ReadKey();
        }
    }
}